package com.pandora.framework.action;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pandora.common.exception.EduException;
import com.pandora.common.util.StringUtils;
import com.pandora.framework.constant.ResponseConstants;
import com.pandora.framework.util.ServiceUtils;
import com.pandora.framework.vo.ServiceCoreVO;

public abstract class BaseAction implements IAction {

	private ServiceCoreVO serviceCoreVO = null;

	protected String type = "";// 请求类型
	protected String subType = "";// 子类型
	protected String action = "";// 请求接口名
	protected String operateLogNo = "";// 操作日志码
	protected String recordNo = "";// 记录码
	protected String reqIp = "";// 请求IP

	protected String accessid = "";// 通行证ID
	protected String accesskey = "";// 通行证key
	protected String requestType = "";// 请求类型

	protected HttpServletRequest request = null;
	protected HttpServletResponse response = null;

	protected Object reqObject = null;
	protected Map<String, Object> resObject = null;

	public ServiceCoreVO execute(ServiceCoreVO vo) throws EduException {

		this.serviceCoreVO = vo;

		type = vo.getType();
		subType = vo.getSubType();
		action = vo.getAction();
		operateLogNo = vo.getOperateLogno();
		reqIp = vo.getIp();
		accessid = vo.getAccessid();
		accesskey = vo.getAccesskey();
		requestType = vo.getRequestType();
		request = vo.getRequest();
		response = vo.getResponse();
		resObject = new LinkedHashMap<String, Object>();

		return execute();
	}

	protected ServiceCoreVO response() {

		if (resObject == null || resObject.isEmpty()) {
			return doResponse(ResponseConstants.SUCCESS);
		}

		return doResponse(resObject);
	}

	/**
	 * 处理响应
	 * 
	 * @param code
	 * @return
	 */
	protected ServiceCoreVO doResponse(Object obj) {

		if (StringUtils.isNotEmpty(recordNo)) {
			serviceCoreVO.setRecordNo(recordNo);
		}

		serviceCoreVO.setResObject(obj);

		return serviceCoreVO;
	}

	/** 初始化参数封装 */
	protected Object init() throws EduException {

		return init(true);
	}

	/**
	 * 获取请求体中参数内容
	 * 
	 * @param name
	 * @return
	 * @throws EduException
	 */
	protected String getRequestContenValue(String key) throws EduException {

		return ServiceUtils.getRequestContentValue(reqObject, key);
	}

	protected Object init(boolean checkFlag) throws EduException {

		if (checkFlag) {
			reqObject = serviceCoreVO.getReqObject();
			if (reqObject == null) {
				throw new EduException(ResponseConstants.REQUEST_CONTENT_ERROR);
			}
		}

		return initData();
	}

	/** 具体接口实现子类执行业务操作 */
	public abstract ServiceCoreVO execute() throws EduException;

	/** 初始化请求参数 */
	public abstract Object initData() throws EduException;
}